<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/1/17
 * Time: 14:20
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\api\controller;

use app\api\model\mysql\MallAccountLog;
use app\api\model\mysql\MallOrder;
use app\api\model\mysql\MallSetting;
use app\common\lib\ArrClass;
use app\common\lib\Show;
use app\common\lib\Status;
use app\api\model\mysql\MallUser;
use think\Exception;
use think\facade\Log;

class Login extends Base
{
    /**
     * @return \think\response\Json
     */
    public function getUserInfo()
    {
        $code = $this->request->param('code', '', 'trim');
        try {
            $user = $this->mini_app->auth->session($code);
        } catch (\Exception $e) {
            Log::error("login-user:" . $e->getMessage());
            return Show::json_show(Status::mini_error, "内部错误");
        }
        if (!empty($user['errcode'])) {
            Log::error("login_auth:" . Show::json_encode($user));
            return Show::json_show(Status::mini_error, "系统内部错误");
        }
        if (empty($user['openid'])) {
            return Show::json_show(Status::mini_error, "程序错误");
        }
        $withoutField = 'delete_time,update_time';
        try {
            $res = (new MallUser())->where('openid', $user['openid'])
                ->withoutField($withoutField)
                ->find();
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "发生错误");
        }
        if ($res) {
            $result = $res->toArray();
        } else {
            try {
                $ret = (new MallUser())->save([
                    'openid' => $user['openid'],
                    "type" => 0
                ]);
            } catch (\Exception $e) {
                return Show::json_show(Status::mini_error, "内部错误");
            }
            if ($ret) {
                try {
                    $res_data = (new MallUser())->where('openid', $user['openid'])
                        ->withoutField($withoutField)
                        ->find();
                } catch (\Exception $e) {
                    return Show::json_show(Status::mini_error, "发生错误");
                }
                if ($res_data) {
                    $result = $res_data->toArray();
                } else {
                    return Show::json_show(Status::mini_error, "数据不存在");
                }
            } else {
                return Show::json_show(Status::mini_error, "操作失败");
            }
        }

        return Show::json_show(Status::mini_normal, "ok", $result);
    }

    /**
     *
     * @return \think\response\Json
     * @throws Exception
     */
    public function image(){
        if (!$this->request->isPost()) {
            throw new Exception("请求类型错误", 400);
        }
        $file = $this->request->file();
        if (empty($file)) {
            return Show::json_show(Status::mini_error, "请上传图片");
        }
        $key = array_keys($file);
        $arrType = ArrClass::uploadAttr();
        try {
            $objClass = ArrClass::initClass($key[0], $arrType, [], true);
            $res = $objClass->upload($this->request);
        }catch (\Exception $e){

            return Show::json_show(Status::mini_error,$e->getMessage(),[],400);
        }
        if($res){
            return Show::json_show(Status::mini_normal,"上传成功",[
                "url"=>(string)url('/'.$res,[],false,true)
            ]);// tp6自带全路径
        }else{
            return Show::json_show(Status::mini_error,'上传失败！请重试');
        }
    }

    /**
     * 月底统计入账团队业绩
     * @return \think\response\Json|void
     * @throws Exception
     */
    public function commissionAll(){
        // 月底最后一天
        //$lastday = date("t", mktime(0, 0, 0, 3));

        try{
            // 所有的已完成订单，未入账订单
           $orders=(new MallOrder())->field('id,openid,againprice')->where([['orderstatus','=',3],['isget','=',0],['againprice','>',0]])->select()->toArray();
           $set=(new MallSetting())->getSettingInfo('teamset');
        }catch (\Exception $e){
            Log::error("user_update:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error,'查询失败');
        }

        if(empty($set)){
            $set['option_value'] =0;
        }
        if($orders){
            $ordermodel =(new MallOrder());
            $ordermodel->startTrans();
            try{
                foreach ($orders as $k=>$v){
                    $user =(new MallUser())->alias('u')
                        ->field('u.openid')
                        ->join('mall_user m','m.parent_id=u.id')
                        ->where("m.openid",$v['openid'])
                        ->find();
                    $money =round($v['againprice']*$set['option_value']/100,2) ?? 0;
                    (new MallAccountLog())->saveAccoutLog($v['id'],$user['openid'],round($v['againprice'],2),4,'下级会员复购奖励');
                    (new MallAccountLog())->saveAccoutLog($v['id'],$user['openid'],$money,5,'团队复购奖励');
                    (new MallOrder())->where("id",$v['id'])->save(array('isget'=>1));
                }
            }catch (\Exception $e){
                Log::error("user_update:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
                $ordermodel->rollback();
                return Show::json_show(Status::mini_error,'查询失败');
            }
            $ordermodel->commit();
        }
        return Show::json_show(Status::mini_normal, "ok", []);
    }


}